﻿namespace Sina.Weibo
{
    using System;
    using System.Collections.Generic;
    using System.Collections.Specialized;
    using System.Diagnostics;
    using System.Web;

    /// <summary>
    /// A utility class that handles read and write operations on current web session.
    /// </summary>
    internal static class HttpContextUtility
    {
        /// <summary>
        /// Reads authorization code from current session.
        /// </summary>
        public static bool ReadAuthCodeRequest(
            HttpContextBase webContext, 
            out string code, 
            out string state, 
            out WeiboAuthException error)
        {
            Debug.Assert(webContext != null, "webContext is null.");

            NameValueCollection queryString = webContext.Request.QueryString;

            code = queryString[AuthConstants.Code];
            bool isCodeRequest = !string.IsNullOrEmpty(code);

            string clientState = queryString[AuthConstants.State];
            IDictionary<string, string> states = WeiboAuthUtility.DecodeAppRequestStates(clientState);
            state = states.ContainsKey(AuthConstants.State) ? states[AuthConstants.State] : null;

            string errorCode = string.Empty;
            string errorDescription = queryString[AuthConstants.QueryParameter];
            error = string.IsNullOrEmpty(errorDescription) ? null : new WeiboAuthException(errorCode, errorDescription, state);

            return isCodeRequest;
        }

        /// <summary>
        /// Writes the user current session.
        /// </summary>
        public static void UpdateUserSession(
            HttpContextBase httpContextBase, 
            WeiboLoginResult loginResult)
        {
            throw new NotImplementedException();
        }
    }
}
